<template>
  <div>
    <el-form ref="form" :inline="true" label-width="100px" class="mt-20 searchbar-box clearfix mb-10">
      <el-button class="mr-10" @click="add('add')" type="primary" icon="el-icon-plus">添加</el-button>
    </el-form>
    <el-table :data="tableData" :empty-text="emptyText" v-loading="isLoading" element-loading-text="加载中..." stripe="stripe">
      <template v-for="(item, index) of tableColumn">
        <el-table-column
          :key="index + item.prop"
          :label="item.title"
          align="center"
          :show-overflow-tooltip="true"
          :min-width="item.minWidth"
          :width="item.width">
          <template slot-scope="scope">
            <span v-if="item.prop === 'updateTime'">{{ getTime(scope.row.updateTime) }}</span>
            <div v-else-if="item.prop==='operation'">
              <el-tooltip class="item" content="上架" placement="top-start">
                <svg-icon v-if="scope.row.available === 0" class="can-click" icon-class="grounding" @click="listing(scope.row)" />
              </el-tooltip>
              <el-tooltip class="item" content="下架" placement="top-start">
                <svg-icon v-if="scope.row.available === 1" class="can-click" icon-class="offshelf" @click="delist(scope.row)" />
              </el-tooltip>
              <el-tooltip class="item" content="编辑" placement="top-start">
                <svg-icon @click="edit('edit', scope.row)" class="can-click" icon-class="note" />
              </el-tooltip>
              <el-tooltip class="item" content="删除" placement="top-start">
                <svg-icon @click="handelDelete(scope.row)" class="can-click" icon-class="delete" />
              </el-tooltip>
            </div>
            <span v-else>{{scope.row[item.prop]}}</span>
          </template>
        </el-table-column>
      </template>
    </el-table>
    <el-pagination
      class="mt-30"
      :current-page="searchParams.currentPage"
      :page-size="searchParams.pageSize"
      :total="total"
      layout="sizes, total, prev, pager, next, jumper"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange">
    </el-pagination>
    <form-wrap ref="form" @submit="submit" :title="title"></form-wrap>
  </div>
</template>

<script>
  import formWrap from '@/components/form';
  import { getSession } from '@/utils'
  export default {
    name: 'courseManage',
    components: { formWrap },
    data () {
      return {
        isLoading: false,
        emptyText: '加载中...',
        tableColumn: [
          { title: '课程名称', prop: 'courseTitle', minWidth: '100', width: null },
          { title: '课程分类', prop: 'courseType', minWidth: '', width: null },
          { title: '上传时间', prop: 'updateTime', minWidth: '', width: null },
          { title: '操作', prop: 'operation', minWidth: '100', width: '' }
        ],
        tableData: [],
        total: 0,
        searchParams: {
          currentPage: 1,
          pageSize: 20
        },
        id: '',
        classificationSelect: [],
        title: '添加课程',
      };
    },
    mounted () {
      this.getDataList();
      // 获取课程分类
      this.getCourseClass();
    },
    methods: {
      /* 获取列表数据 */
      getDataList (currentPage) {
        this.isLoading = true;
        this.searchParams.currentPage = currentPage || 1;
        let param = {
          currentPage: this.searchParams.currentPage,
          pageSize: this.searchParams.pageSize,
          id: this.id,
        }
        this.$api.course.courseList(param).then(res => {
          this.isLoading = false;
          this.total = res.total;
          this.tableData = res.data || [];
          this.emptyText = !this.tableData.length ? '暂无数据' : this.emptyText;
        });
      },
      getCourseClass(){
        let param = {
          currentPage: 1,
          pageSize: 999
        };
        this.$api.course.courseClassification(param).then(res => {
          this.classificationSelect = res.data || [];
          if(this.classificationSelect.length){
            this.classificationSelect.forEach((item)=>{
              this.$set(item, 'label', item.courseType);
              this.$set(item, 'value', item.id);
            })
          }
        });
      },
      /**
      * 新增
      **/
      add(){
        let labelList = [
          { label: '课程名称', prop: 'courseTitle', type: 'input', required: true },
          { label: '课程分类', prop: 'courseTypeId', type: 'select', required: true, select: this.classificationSelect },
        ];
        this.$refs.form.showDialog(labelList);
      },
      /* 编辑 */
      edit (type, obj) {
        this.$router.push({
          path: '/courseDetail',
          query: {
            courseId: (obj && obj.id) ? obj.id : '',
            type: type
          }
        })
      },
      submit(form){
        let param = {
          courseTitle: form.courseTitle,
          courseTypeId: form.courseTypeId,
          createUser: getSession('userId'),
          courseImgUrl: '',
          courseIntroduction: '',
          courseContent: '',
          sort: '',
          remark: '',
          available: 0,
        }
        this.$api.course.courseOverviewAdd(param).then(res => {
          if(res.status.code === 200){
            this.$message.success('添加成功');
            this.$refs.form.cancel();
            this.getDataList();
          }
        });
      },
      /* 删除 */
      handelDelete (obj) {
        this.$confirm(`确定要删除${obj.courseTitle}这个课程?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$api.course.courseOverviewDel({
            id: obj.id,
          }).then(() => {
            this.$message({
              type: 'success',
              message: `删除成功!`
            });
            this.getDataList()
          })
        }).catch(() => {
        });
      },
      handleCurrentChange (val) {
        this.searchParams.currentPage = val
        this.getDataList(val)
      },
      handleSizeChange (val) {
        this.searchParams.pageSize = val
        // this.searchParams.currentPage = 1
        this.getDataList()
      },
      getTime(val){
        if(val){
          return this.Moment(val).format('YYYY-MM-DD HH:mm:ss')
        }else {
          return ''
        }
      },
      // 上架
      listing(row){
        let param = {
          id: row.id,
          available: 1
        };
        this.$api.course.courseUpdate(param).then(res => {
          if(res.status.code === 200){
            this.$message.success('上架成功');
            this.getDataList()
          }
        });
      },
      // 下架
      delist(row){
        this.$confirm(`确定要下架吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {
            id: row.id,
            available: 0
          };
          this.$api.course.courseUpdate(param).then(res => {
            if(res.status.code === 200){
              this.$message.success('下架成功');
              this.getDataList()
            }
          });
        }).catch(() => {});
      },
    }
  }
</script>
